package com.ztesoft.huangfu.learning.springboot.springbootwebflux.controller;

import com.ztesoft.huangfu.learning.springboot.springbootwebflux.entity.City;
import com.ztesoft.huangfu.learning.springboot.springbootwebflux.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;

import java.util.function.Consumer;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/6/12
 * Time: 19:12
 * Version: 1.0
 * Description:
 * 参考：https://zhuanlan.zhihu.com/p/30813274
 * http://www.lupaworld.com/article-263775-1.html
 **/
@RestController
@RequestMapping(value = "/city")
public class CityRestController {
    @Autowired
    private CityService cityService;

    @GetMapping("/findOneCity/{id}")
    public Mono<City> findOneCity(@PathVariable("id") Long id) {
        return Mono.create(new Consumer<MonoSink<City>>() {
            @Override
            public void accept(MonoSink<City> monoSink) {
                monoSink.success(cityService.findCityById(id));
            }
        });
//        return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.findCityById(id)));
    }

    @GetMapping("/findAllCity")
    public Flux<City> findAllCity() {
//        Flux<City> city = (Flux<City>)cityService.findAllCity();
        return Flux.create(cityFluxSink -> {
            cityService.findAllCity().forEach(city -> {
                cityFluxSink.next(city);
            });
            cityFluxSink.complete();
        });
    }

    @PostMapping("/createCity")
    public Mono<Long> createCity(@RequestBody City city) {

        return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.saveCity(city)));
    }

    @PutMapping("/modifyCity")
    public Mono<Long> modifyCity(@RequestBody City city) {
        return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.updateCity(city)));
    }

    @DeleteMapping("/modifyCity/{id}")
    public Mono<Long> modifyCity(@PathVariable("id") Long id) {

        return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.deleteCity(id)));
    }
}
